package com.sixuan.rabbitmqprovider.workmode.workqueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


/**
 * RabbitMq工作模式：Work Queues：多个消费者共同承担消息的消费任务（默认轮询算法）
 * Created by LENOVO on 2020-7-8 15:59
 *
 * @author LENOVO
 */
public class WorkQueuesProvider {
    private static final String rabbitMqHost = "47.97.195.191";
    private static final int rabbitMqPort = 5672;
    private static final String username = "guest";
    private static final String password = "guest";

    private static final String QUEUE_NAME = "WorkQueuesQueue";

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(rabbitMqHost);
        connectionFactory.setPort(rabbitMqPort);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection();
            channel = connection.createChannel();
            //声明队列
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            //发送消息
            for (int i = 0; i < 20; i++) {
                String msg = "Hello World!" + i;
                channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
                System.out.println("Send to consumer finished ! message：" + msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
